package main

import (
	"fmt"
	"io"
	"log"
	"net"
)

func main() {
	log.Println("program start ,start listening port：10020")
	ln,err := net.Listen("tcp","127.0.0.1:10020")
	if err != nil{
		log.Printf("listen error：%v",err)
		return
	}
	for{
		conn,err := ln.Accept()
		if err != nil{
			log.Printf("connection error：%d",err)
			continue
		}else {
			log.Printf("user:%v connect success！",conn.RemoteAddr())
		}
			go process(conn)
	}
}

func process(conn net.Conn) {
	defer conn.Close()
	for {
		buf := make([]byte, 512)
		n, err := conn.Read(buf)
		if err != nil {
			if err == io.EOF{
				log.Println("connection disconnected")
			}else {
				log.Println("read failed, err:", err)
			}
			return
		}
		conn.Write([]byte("message received!"))
		fmt.Printf("recieved message from user:%v >>> %v\n",conn.RemoteAddr(),string(buf[:n]))
		//fmt.Println(buf[:n])
	}
}